package com.cssw.fyzb.busi.api.user;

import com.cssw.fyzb.busi.service.pay.PayService;
import com.cssw.fyzb.busi.service.system.SysParamService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.PayOrder;
import com.cssw.fyzb.core.model.dodb.User;
import com.ijpay.core.kit.PayKit;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Author zhouxu
 * @create 2021-01-22 20:36
 */
@Function(description = "实名认证支付-支付宝", parameters = {
        @Parameter(name = "userId", type = Type.Integer, description = "用户标识", required = true),
})
@Component
public class UserAuthPay implements Action {

    private static final Logger logger = LoggerFactory.getLogger(UserAuthPay.class);

    @Autowired
    private PayService payService;

    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleLockFactory simpleLockFactory;

    @Value("${pay.interval.sec:30}")
    private int payIntervalSec;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");

        SimpleLock simpleLock = simpleLockFactory.getLock("USER_"+userId);

        try {
            simpleLock.acquire();
            User user = userService.getById(userId);
            if (user.isPayAuth()) {
                return Response.fail("支付认证已通过，无需认证");
            }

            if (!user.isFace()) {
                return Response.fail("人脸信息未认证，请先认证人脸");
            }

            // 随机订单号
            String outTradeNo = PayKit.generateStr();
            String payAmount = sysParamService.findByCode("AUTH_FEE").getParamValue();

//            PayOrder order = payService.findByUserPayAuthOrder(userId);
//            if (order == null) {
            //提交一次就生成一条
            PayOrder order = payService.createPayOrder(userId, Integer.parseInt(payAmount), PayOrder.PAY_USER_AUTH,
                        outTradeNo, PayOrder.PAY_Ali, null);
//            } else {
//                if (order.isPayFinished()) {
//                    return Response.fail("订单已支付，无需重复支付");
//                }
//
//                //支付必须间隔1分钟以上
//                if (null != order.getUpdateTime()){
//                    long lastUpMills = order.getUpdateTime().getTime() + payIntervalSec * 1000;
//                    long currMills = System.currentTimeMillis();
//                    if (currMills < lastUpMills){
//                        return Response.fail("支付太频繁了，请稍后再试");
//                    }
//                }
//
//                payService.updatePayOrderInit(order, outTradeNo);
//            }
            //  调起第三方支付
            BigDecimal authAmount = new BigDecimal(payAmount).divide(new BigDecimal(100)).setScale(2);
            return payService.aliAdapay(order, "人脸认证费用", "认证费用：" + authAmount.toString());
        } catch (BizException biz) {
            logger.error(biz.getErrMsg(), biz.getErrCode());
            return Response.fail(biz.getErrMsg(), biz.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("支付发起失败");
        } finally {
            try {
                simpleLock.release();
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }

}
